import SparkMD5 from 'spark-md5';

/**
 * async和await成功失败捕捉
 * @param {*} promise
 * @returns
 */
export function awaitCatch(promise) {
  return promise.then((res) => res).catch((err) => err);
}

/**
 * 采用JSON.parse(JSON.stringify())方式简单克隆
 * @param {*} param
 * @returns
 */
export function jsonClone(param) {
  if (!param && param !== 0) return undefined;
  return JSON.parse(JSON.stringify(param));
}

/**
 * 获取文件的md5值
 * @author liuyc
 * @param {obj} file
 */
export function getFileMd5(file) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    const spark = new SparkMD5.ArrayBuffer();
    fileReader.readAsArrayBuffer(file);
    fileReader.onload = e => {
      spark.append(e.target.result);
      const md5 = spark.end();
      resolve(md5);
    };
  });
}

/**
 * 防抖
 * @param {function} func 
 * @param {number} delay 
 * @returns 
 */
export function debounce(func,delay){
  var timer = null
  return function(...args){
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(()=>{
      func(...args)
    },delay)
  }
}

// 使用时间戳实现节流
export function throttleByTimestamp(func,delay){
  var timestamp = 0
  var args
  return function(){
    var now = new Date()
    args = arguments
    if(now - timestamp > delay){
      func.apply(null,args)
      timestamp = now
    }
  } 
}

// 使用计时器实现节流
export function throttleByTimer(func,delay){
  var timer = null
  var args
  return function(){
    args = arguments
    if(!timer){
      func.apply(null,args)
      timer = setTimeout(()=>{
        timer = null
      },delay)
    }
  }
}